package chat;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class Client implements Commands {

	/**
	 * Basic Chat Client used to demonstrate how to use a Multi-Thread Server and a Client.
	 * @author Collard & Monterrubio
	 *
	 */
		
		/** Socked used to communicate with the Server */
		private Socket _ss;
		
		/** Printer used to Send Information to the Server  */
		private PrintWriter _out;
		
		/** Thread Used to Listen to the Server	 */
		private ListenerThread _listen;
		
		/** Two Text Areas. 1 To print received Messages and One to send them  */
		private JTextArea jta;
		
		//Added by jan
		/**Area to input field*/
		private JTextField input2;
		
		/**Reference to the firstInput for a name*/
		private JTextField userInput;
		/**reference to the name */
		private String userName;
		
		/**A reference to the hostName else localhost*/
		private String hostName = "localhost";
		
		/**Input for hostName or IP address*/
		private JTextField inputIP;
		
		/**Input for portNumber  1713 works fine so does 4242*/
		private JTextField inputPortNo;
		
		/**Reference to our scroll pane */
		private JScrollPane sp;
		
		/**Reference to connect button */
		private JButton connectButton;
		
		/**A reference to the userNameLabel*/
		private JLabel userNameLabel;
		
		/**A reference to the portNumber must be the same as HostingMember */
		private int portNo = 1713;
		/**A reference to the main window */
		private JFrame _main;
		
		/**A reference to the textarea panel*/
		private JPanel _jp;
		
		/**A label for the money we have */
		private JLabel _cashLabel;
		
		/**A reference to our cash*/
		private static int _money;
		
		public String getHostName() {
			return hostName;
		}

		public void setHostName(String hostName) {
			this.hostName = hostName;
		}

		public int getPortNo() {
			return portNo;
		}

		public void setPortNo(int portNo) {
			this.portNo = portNo;
		}

		/**
		 * Runnable Object that is used to create a Thread that listens for a message from the server
		 * @author jcbbjjttt
		 *
		 */
		class ListenerThread implements Runnable{

			/** Reads Data from the Server  */
			private BufferedReader _in;
			
			private ListenerThread(BufferedReader in){
				_in = in;
			}
			
			// THIS METHOD IS CALLED WHEN THE THREAD IS STARTED
			public void run() {
				//PREPARE A STRING TO BE SET WHEN SERVER SENDS A MESSAGE
				String message;
				//WHEN THE SERVER CLOSES ITS SOCKET TO THE CLIENT IT SENDS A NULL Reader
				//SO THE THREAD WILL LEAVE THE LOOP
				while(_in != null){
					try{
						
						
					while((message = _in.readLine()) != null){
						if(message.contains("/send"))
							cashCenter(message);
						
						if(!(message.contains("/")))
						jta.append("\n"+message);
						
						sp.validate();
						_jp.validate();
						
						_main.validate();
					}
					}catch(IOException e){
						//IGNORE AN ERROR MESSAGE IF _in COULD NOT READ
					}
				}			
			}
			
		}
		
		
		/** Sends a message to the PrintWriter which is hopefully connect to the server
		 * @param s Message to Send
		 */
		public void sendMessage(String s){
			if(_out != null){
				//MESSAGE SENDING IS EASY!
				_out.println(s);
			}
		}
		
		/**
		 * CONNECT TO ANOTHER COMPUTER... OR ATLEAST TRY
		 * @param host IP to connect to
		 * @param port Port to connect to
		 * @return <code>true</code> if you connected. <code>false</code> if you could not connect
		 */
		public boolean doConnect(String host, int port){
			try{
				// Set the Socket to try and connect to.
				_ss = new Socket(host, port);
				// Create a PrintWriter to outpur strings to the server
				_out = new PrintWriter(_ss.getOutputStream(), true);				
				//Create a new Listener for the server
				_listen = new ListenerThread(new BufferedReader(new InputStreamReader(_ss.getInputStream())));
				//Start the listener thread...
				new Thread(_listen).start();
				//WOOT! We have lift off!
				return true;
			}catch(Exception e){
				return false;
			}
		}
		
		/** Constructor for Client
		 * 
		 */
		public Client()
		{
			//Remember to initialize your variables! Even in Java!
			_ss = null;
			_out = null;
			//Create the GUI
			initGUI();
		}
		
		/** Some fairly sloppy code to create a Client GUI. You could make it better :-P
		 * 
		 */
		public void initGUI()
	    {
	    	//Main frame
	        _main = new JFrame();
	        _main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	       
	        //Main JPanel
	        _jp = new JPanel(new BorderLayout());
	        JPanel buttonPannel = new JPanel(new BorderLayout(5,5));
	        JPanel userNamePanel = new JPanel();
	        
	        //Add the JPanel to the Main Frame
	        _main.getContentPane().add(_jp);
	        _jp.add(buttonPannel, BorderLayout.SOUTH);
	        
	        _cashLabel = new JLabel();
	        _cashLabel.setText(Integer.toString(_money));
	        
	        //type messages here
	        input2 = new JTextField(14);
	        input2.setToolTipText("Type in message and press enter to send");
	        input2.setEditable(false);
	        
	        //Connection Button
	        connectButton = new JButton("Connect");
	        connectButton.setEnabled(false);
	        //Prompt for IP
	        inputIP = new JTextField(10);
	        inputIP.setText(hostName);
	        inputIP.setToolTipText("Insert IP address, or press enter to play on a local host");
	        inputIP.setEditable(true);
	        
	        inputIP.addKeyListener(new KeyListener(){

				public void keyPressed(KeyEvent arg0) {
					if(arg0.getKeyCode() == KeyEvent.VK_ENTER){
						if(inputIP.getText() == null)
						hostName= "localhost";
						else
						hostName = inputIP.getText();
					inputIP.setEditable(false);
					inputIP.setVisible(false);
					}
				}
				public void keyReleased(KeyEvent arg0) {
				}
				public void keyTyped(KeyEvent arg0) {
					// TODO Auto-generated method stub
					
				}
	        	
	        });
	        userNamePanel.add(inputIP, BorderLayout.WEST);
	        
	        //Prompt for port
	        inputPortNo = new JTextField(10);
	        inputPortNo.setText(Integer.toString(portNo));
	        inputPortNo.setToolTipText("Insert port number or press enter to play on current port");
	        inputPortNo.setEditable(true);
	        
	        inputPortNo.addKeyListener(new KeyListener(){

				public void keyPressed(KeyEvent arg0) {
					if(arg0.getKeyCode() == KeyEvent.VK_ENTER){
						
					setPortNo(Integer.parseInt(inputPortNo.getText()));
					inputPortNo.setEditable(false);
					inputPortNo.setVisible(false);
				}
				}
				public void keyReleased(KeyEvent arg0) {
				}
				public void keyTyped(KeyEvent arg0) {
					// TODO Auto-generated method stub
					
				}
	        	
	        });
	        userNamePanel.add(inputPortNo, BorderLayout.EAST);
	        //Prompt for a UserName
	        userInput = new JTextField(6);
	        userInput.setText("userName");
	        
	        userNameLabel = new JLabel();
	        userNameLabel.setVisible(false);
	        userNamePanel.add(userNameLabel);
	        userInput.setToolTipText("Insert Your userName here");
	        userInput.addKeyListener(new KeyListener(){

				public void keyPressed(KeyEvent arg0) {
					if(arg0.getKeyCode() == KeyEvent.VK_ENTER){
						if(!userInput.getText().equals("")){
						if(!userInput.getText().equals("userName")){
						userName = userInput.getText();
						userNameLabel.setText(userName);
						userInput.setText("");
						userInput.setVisible(false);
						userNameLabel.setVisible(true);
						userInput.setEditable(false);
						connectButton.setEnabled(true);
						}
						}
					}
				}
				public void keyReleased(KeyEvent arg0) {
				}

				public void keyTyped(KeyEvent arg0) {		// TODO Auto-generated method stub	
				}
		       	
	        });
	       
	        userNamePanel.add(userInput);
	        jta = new JTextArea(10, 50);
	        _jp.add(userNamePanel, BorderLayout.NORTH);
	        //fixing scrollbars
	        jta.setCaretPosition(jta.getText().length());
	        jta.setWrapStyleWord(true);
	        jta.setLineWrap(true);
	        _jp.add(jta, BorderLayout.CENTER);
		    // Add the scroll pane the center view of the jp
	        
	        buttonPannel.add(input2, BorderLayout.CENTER);
	        
	        connectButton.addActionListener(
	                new ActionListener() // anonymous inner class
	                 {
	                    // event handler called when JButton is pressed
	                    public void actionPerformed( ActionEvent event )
	                    {
	                    	//doConnect returns false if we could not connect. "localhost" is good for testing
	                    	//on a single computer. Choose a port that is not used alot 4000 is usually good. Also
	                    	//10000
	                    	if(!doConnect(hostName, getPortNo()))
	                    		System.err.println("Could not connect!");
	                    	
	                    	input2.setEditable(true);
	                    	}
	                    } // end anonymous inner class

	              ); // end call to addActionListener          
	        buttonPannel.add(connectButton, BorderLayout.WEST);
		    
	        input2.addKeyListener(new KeyListener(){
				public void keyPressed(KeyEvent e) {
					if(e.getKeyCode() == KeyEvent.VK_ENTER){
						sendMessage(userName.concat(": ").concat(input2.getText()));
						input2.setText("");
					}
					
				}
				public void keyReleased(KeyEvent arg0) {
					// TODO Auto-generated method stub
				}

				public void keyTyped(KeyEvent arg0) {
					// TODO Auto-generated method stub	
				}
	        });
	        //scrollpane addition
		    sp = new JScrollPane (jta);
		    // Always show both horizontal and vertical scroll bars by default.
		    //adds scrollpane
		    
		    sp.setAutoscrolls(true);
		    
		    _jp.add ( sp, BorderLayout.CENTER);
		    _jp.validate();
		    
		    
	        //Makes it a good size
	        _main.pack();
		    jta.validate();
		    sp.validate();
		    _main.validate();
		    userNamePanel.add(_cashLabel, BorderLayout.EAST);
	        //OOOH! I CAN SEEZ IT!
	        _main.setVisible(true);
	       
	       
	    }
		
		//Great Main Method! This is generally what a main should look like for a program :)
		public static void main(String args[])
		{
			_money = 100;
			new Client();
		}
		
	
	@Override
	public void muteList() {
		// TODO Auto-generated method stub

	}

	@Override
	public void muteUser(String user) {
		// TODO Auto-generated method stub

	}

	@Override
	public void reMessage(String user) {
		// TODO Auto-generated method stub

	}

	@Override
	public void scores() {
		// TODO Auto-generated method stub

	}

	@Override
	public void sendAll(int allCash, Object allTower, String user) {
		// TODO Auto-generated method stub

	}

	@Override
	public void sendPrivateMessage(String user) {
		// TODO Auto-generated method stub

	}

	@Override
	public void sendTower(Object tower, String user) {
		// TODO Auto-generated method stub

	}

	@Override
	public void time() {
		// TODO Auto-generated method stub

	}

	@Override
	public void userList() {
		// TODO Auto-generated method stub

	}

	@Override
	public void voteUser(String user) {
		// TODO Auto-generated method stub

	}
	
	public void cashCenter(String m){
		String sender;
		int sendEnd = m.indexOf(":");
		sender = m.substring(0, sendEnd);
		m = m.substring(sender.length());
		m = m.replaceAll(": /send ", "");
		String receiver = m;
		int recEnd = m.indexOf(" ");
		receiver = receiver.substring(0, recEnd);
		String amount;
		amount = m.substring(recEnd+1);
		
		int num = Integer.parseInt(amount);
		if(userName.equals(sender)){
			if(num <= _money)
				{  	_money -= num;
					_cashLabel.setText(Integer.toString(_money));
					_cashLabel.validate();
				}
			jta.append("/n"+"You don't have enough funds!!!");
		}
		if(userName.equals(receiver)){
			_money += num;
			_cashLabel.setText(Integer.toString(_money));
			_cashLabel.validate();
		}
	}

	@Override
	public void sendMoney(String cash, String user) {
		// TODO Auto-generated method stub
		
	}

}
